//
//  Hear_CustomTextView.m
//  Hear
//
//  Created by mac on 2018/4/26.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_CustomTextView.h"

@implementation Hear_CustomTextView {
    UIColor *_contentColor;
    BOOL _editing;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        _contentColor = FirstTextColor;
        _editing = NO;
        _placeholderColor = FirstTextColor;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishEditing:) name:UITextViewTextDidEndEditingNotification object:self];
    }
    return self;
}

#pragma mark - super

- (void)setTextColor:(UIColor *)textColor {
    [super setTextColor:textColor];
    _contentColor = textColor;
}

- (NSString *)text {
    if ([super.text isEqualToString:_placeholder] && super.textColor == _placeholderColor) {
        return @"";
    }
    return [super text];
}

- (void)setText:(NSString *)string {
    if (string == nil || string.length == 0) {
        return;
    }
    super.textColor = _contentColor;
    [super setText:string];
}


#pragma mark - setting
- (void)setPlaceholder:(NSString *)string {
    _placeholder = string;
    [self finishEditing:nil];
}


#pragma mark - notification
- (void)startEditing:(NSNotification *)notification {
    _editing = YES;
    if ([super.text isEqualToString:_placeholder]) {
        super.textColor = _contentColor;
        super.text = @"";
    }
}

- (void)finishEditing:(NSNotification *)notification {
    _editing = NO;
    if (super.text.length == 0) {
        super.textColor = _placeholderColor;
        super.text = _placeholder;
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
